package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;


    /**
     * 新增报警规则
     *
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 校验设备上报数据，进行报警规则过滤处理
     *
     * @param deviceDataVo 设备上报数据
     */
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        //获取设备上报数据时间，如果上报发生在1分钟前，为历史数据，不再处理
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }

        //查询报警规则，将对于全部设备的报警规则 和 对于本设备的报警规则合并
        List<AlertRule> allDeviceAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        List<AlertRule> theDeviceAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        Collection<AlertRule> alertRules = CollUtil.addAll(allDeviceAlertRules, theDeviceAlertRules);

        //如果报警规则为空，程序结束
        if (CollectionUtil.isEmpty(alertRules)) {
            return;
        }

        //如果报警规则不为空，遍历报警规则，进行校验
        alertRules.forEach(alertRule -> deviceDateAlarmHandler(deviceDataVo, alertRule));
    }

    @Autowired
    private UserRoleMapper userRoleMapper;

    //设备维护人员的角色名称
    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    //超级管理员的角色名称
    @Value("${zzyl.alert.managerRole}")
    private String managerRole;

    /**
     * 设备数据报警处理器
     *
     * @param deviceDataVo 设备上报数据
     * @param alertRule    报警规则
     */
    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //第一层校验：判断是否在生效时段内
        String[] aepArr = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(aepArr[0]);
        LocalTime endTime = LocalTime.parse(aepArr[1]);
        //上报时间
        LocalTime time = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();

        //如果上报时间不在生效时间段内，校验结束
        if (startTime.isAfter(time) || endTime.isBefore(time)) {
            return;
        }

        //设备id
        String iotId = deviceDataVo.getIotId();
        //从redis中获取数据，报警规则连续触发次数rediskey
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX +
                iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();

        //第二层校验：将设备上报值和阈值比较
        //x – 第一个值，y – 第二个值。x==y返回0，x<y返回小于0的数，x>y返回大于0的数
        int compareResult = NumberUtil.compare(Double.parseDouble(deviceDataVo.getDataValue()), alertRule.getValue());
        //或 逻辑运算，2个条件满足其一即为true
        //1.运算符为>=，且设备上报值 >= 阈值
        //2.运算符为<，且设备上报值 < 阈值
        if ((ObjectUtil.equals(alertRule.getOperator(), ">=") && compareResult >= 0)
                || (ObjectUtil.equals(alertRule.getOperator(), "<") && compareResult < 0)) {
            log.debug("此时设备上报数据达到阈值");
        } else {
            //该情况不符合报警规则，所以设备上报数据为正常数据。需要删除redis聚合的异常数据,程序结束
            redisTemplate.delete(aggCountKey);
            return;
        }

        //第三层校验：校验当前设备+功能的报警规则是否处于沉默周期
        String silentCacheKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentCacheKey);
        //如果redis中存在对应沉默周期数据，则当前设备+功能正处于沉默周期，无需报警
        if (StringUtils.isNotEmpty(silentData)) {
            return;
        }

        //第四层校验：校验持续周期
        //4.1获取连续触发报警规则的次数
        //aggCountData是上次触发报警累计到的次数，这一次又触发了报警，所以累积到这次就+1
        String aggCountData = redisTemplate.opsForValue().get(aggCountKey);
        int triggerCount = ObjectUtil.isEmpty(aggCountData) ? 1 : Integer.parseInt(aggCountData) + 1;

        //4.2判断次数是否与持续周期相等
        //如果触发报警规则次数不等于持续周期，则无需报警
        if (ObjectUtil.notEqual(alertRule.getDuration(), triggerCount)) {
            redisTemplate.opsForValue().set(aggCountKey, triggerCount + "");
            return;
        }

        //如果触发报警规则次数等于持续周期，则需要报警，完成以下操作：
        //1）删除报警规则连续触发次数的缓存
        //2）添加对应的沉默周期，设置过期时间添加对应的沉默周期，设置过期时间
        //3）报警数据存储到数据库
        redisTemplate.delete(aggCountKey);
        redisTemplate.opsForValue().set(silentCacheKey, deviceDataVo.getDataValue(), alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

        //获取消息的消费者
        List<Long> consumerIds = null;
        if (ObjectUtil.equals(0, alertRule.getAlertDataType())) {
            //如果是老人报警数据，需要通知绑定老人的护理员。根据iotId查询老人绑定的护理员
            if(deviceDataVo.getLocationType() == 0){
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
            }else if(deviceDataVo.getPhysicalLocationType() == 2){
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
            }
        } else {
            //如果是设备报警数据，需要通知设备维护人员。根据指定角色名称查询相关用户
            consumerIds = userRoleMapper.selectByRoleName(deviceMaintainerRole);
        }
        //查询超级管理员，超级管理员无论什么消息都会接收
        List<Long> managerIds = userRoleMapper.selectByRoleName(managerRole);
        List<Long> allConsumerIds = CollUtil.addAllIfNotContains(consumerIds, managerIds);

//        //新增报警数据
//        insertAlertData(deviceDataVo, alertRule, allConsumerIds);
        //保存报警数据
        List<AlertData> list = insertAlertData(allConsumerIds, alertRule, deviceDataVo);

        //获取需要推送的用户id列表
        List<Long> userIds = list.stream().map(AlertData::getUserId).collect(Collectors.toList());

        //发送websocket消息
        websocketNotify(alertRule, list.get(0), userIds);

    }

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 发送websocket通知
     *
     * @param alertRule 报警规则
     * @param alertData 报警数据
     */
    private void websocketNotify(AlertRule alertRule, AlertData alertData, List<Long> userIds) {
        // websocket通知：弹窗消息
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(alertRule.getFunctionName());
        alertNotifyDto.setAlertDataType(alertData.getType());
        alertNotifyDto.setNotifyType(1);
        //给指定消费者发送消息
        webSocketServer.sendMessageToConsumer(alertNotifyDto, userIds);
    }

    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 保存报警数据
     *
     * @param allIds
     * @param rule
     * @param deviceDataVo
     */
    private List<AlertData> insertAlertData(List<Long> allIds, AlertRule rule, DeviceDataVo deviceDataVo) {
        //对象拷贝
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(rule.getId());
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", rule.getFunctionName(), rule.getOperator(), rule.getValue(), rule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setStatus(0);//待处理
        alertData.setType(rule.getAlertDataType());
        //遍历ids
        List<AlertData> list = allIds.stream().map(userId -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(userId);
            return dbAlertData;
        }).collect(Collectors.toList());

        //批量保存
        alertDataMapper.batchInsert(list);

        return list;

    }
}
